﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Model;
using RecruitStudents.Client.BLL;
using RecruitStudents.Utility.Helper;

namespace RecruitStudents.Client.OnSiteSign
{
    public partial class ExamRoomUserControl : UserControl
    {
        ServiceOnSiteSign _OnSiteSignService = null;
        public ServiceOnSiteSign OnSiteSignServiceAttr
        {
            get
            {
                if (_OnSiteSignService == null)
                {
                    _OnSiteSignService = new ServiceOnSiteSign();
                }
                return _OnSiteSignService;
            }
            set
            {
                _OnSiteSignService = value;
            }
        }

        ServiceComm _ServiceControlDataSource = null;
        public ServiceComm ServiceControlDataSourceAttr
        {
            get
            {
                if (_ServiceControlDataSource == null)
                {
                    _ServiceControlDataSource = new ServiceComm();
                }
                return _ServiceControlDataSource;
            }
            set
            {
                _ServiceControlDataSource = value;
            }
        }

        public delegate void DistributionEventHandler(object sender, EventArgs e);
        public delegate void DoubleClickEventHandler(object sender, EventArgs e);
        public delegate void ExamRoom_DragEnterEventHandler(object sender, DragEventArgs e);
        public delegate void ExamRoom_DragDropEventHandler(object sender, DragEventArgs e);
        public delegate void OnSiteSign_RefreshEventHandler(object sender, EventArgs e);



        public override string Text { get { return this.groupControl1.Text; } set { this.groupControl1.Text = value; } }
        public string ExamRoomName { get; set; }
        public string ExamRoomId { get; set; }
        public string SignedID { get; set; }
        public string FreshTime { get; set; }
        public int MaxCount { get { return cmbMaxCount.Text.ToSafeInt(); } }
        public bool IsAddDataDistri
        {
            get
            {
                int ExamCount = MaxCount;
                int iMax = GetQueueCount(ExamRoomId);
                int iDiffer = ExamCount - iMax;
                if (iDiffer > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public event DistributionEventHandler Distribution;
        public event DoubleClickEventHandler GridViewDoubleClick;
        public event ExamRoom_DragEnterEventHandler ExamRoom_DragEnter;
        public event ExamRoom_DragDropEventHandler ExamRoom_DragDrop;
        public event OnSiteSign_RefreshEventHandler SiteSign_Refresh;

        protected void OnSiteSign_Refresh(object sender, EventArgs e)
        {
            if (SiteSign_Refresh != null)
            {
                SiteSign_Refresh(sender, e);
            }
        }


        protected void OnExamRoom_DragEnter(object sender, DragEventArgs e)
        {
            if (ExamRoom_DragEnter != null)
            {
                ExamRoom_DragEnter(sender, e);
            }
        }
        protected void OnExamRoom_DragDrop(object sender, DragEventArgs e)
        {
            if (ExamRoom_DragDrop != null)
            {
                ExamRoom_DragDrop(sender, e);
            }
        }
        protected void OnDistribution(object sender, EventArgs e)
        {
            if (Distribution != null)
            {
                Distribution(sender, e);
            }
        }
        protected void OnGridViewDoubleClick(object sender, EventArgs e)
        {
            if (GridViewDoubleClick != null)
            {
                GridViewDoubleClick(sender, e);
            }
        }
        public ExamRoomUserControl()
        {
            InitializeComponent();
            this.chkLock.CheckedChanged += this.chkLock_CheckedChanged;
            this.btn_Distribution.Click += this.btn_Distribution_Click;
            this.gridControl2.DragDrop += this.gridControl2_DragDrop;
            this.gridControl2.DragEnter += this.gridControl2_DragEnter;
            this.gridView2.RowCellClick += this.gridView2_RowCellClick;
            gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView2.OptionsSelection.EnableAppearanceFocusedRow = false;
            gridView2.OptionsSelection.EnableAppearanceHideSelection = false;
            timer_Queue.Enabled = false;
        }


        public ExamRoomUserControl(string examRoomId, string examRoomName, ServiceOnSiteSign _onsitesignService,
            ServiceComm _servicecontrolDataSource)
            : this()
        {
            ExamRoomId = examRoomId;
            ExamRoomName = examRoomName;
            this.OnSiteSignServiceAttr = _onsitesignService;
            this.ServiceControlDataSourceAttr = _servicecontrolDataSource;
            using (DataTable dtTeach = ServiceControlDataSourceAttr.GetTeacherList(examRoomId))
            {
                lbTeachName.Text = string.Empty;
                if (dtTeach != null)
                {
                    foreach (DataRow dr in dtTeach.Rows)
                    {
                        if (lbTeachName.Text.Length == 0)
                        {
                            lbTeachName.Text = dr["ExaminerName"].ToSafeString();
                        }
                        else
                        {
                            lbTeachName.Text = lbTeachName.Text + "," + dr["ExaminerName"].ToSafeString();
                        }
                    }
                }
            }
        }

        private void btn_Distribution_Click(object sender, EventArgs e)
        {
            OnDistribution(this, e);
            DataGridBind();
        }

        private void gridView2_DoubleClick(object sender, EventArgs e)
        {
            if (gridView2.GetFocusedValue() != null)
            {
                OnGridViewDoubleClick(this, e);
            }
        }

        public void DataGridBind()
        {
            using (DataTable dt = OnSiteSignServiceAttr.GetCombinationData(ExamRoomId, Utility.Helper.SessionerHelper.SystemYear))
            {
                gridControl2.DataSource = dt;
            }
        }

        private void gridControl2_DragDrop(object sender, DragEventArgs e)
        {
            if (!string.IsNullOrEmpty(SignedID))
            {
                OnSiteSignServiceAttr.SavePadQueueBySignedID(SignedID, ExamRoomId);
                DataGridBind();
            }
            OnExamRoom_DragDrop(sender, e);
        }

        private void gridControl2_DragEnter(object sender, DragEventArgs e)
        {
            OnExamRoom_DragEnter(sender, e);
            if (!string.IsNullOrEmpty(SignedID))
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void chkLock_CheckedChanged(object sender, EventArgs e)
        {
            if (chkLock.Checked)
            {
                cmbMaxCount.Enabled = false;
            }
            else
            {
                cmbMaxCount.Enabled = true;
            }
        }

        public void SetTimerQueueEnabled(bool IsEnabled)
        {
            if (IsEnabled)
            {
                iTimer = iConstTime;
                //if (FreshTime == null || FreshTime == "")
                //{
                //    FreshTime = "1";
                //}
                //iTimer = int.Parse(FreshTime) * 60;
            }
            else
            {
                btn_Distribution.Text = "分配";
            }
            timer_Queue.Enabled = IsEnabled;
        }

        private void ZDFP()
        {
            bool isFP = IsAddDataDistri;
            if (isFP)
            {
                using (DataTable dt = OnSiteSignServiceAttr.GetTB_Pad_SignedTable_New(SessionerHelper.ExaminationID, SessionerHelper.SystemYear))
                {
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        Distribute(dt.Rows[0]);
                    }
                    else
                    {
                        isFP = false;
                    }
                }
            }
            if (isFP)
            {
                ZDFP();
            }
        }
        private const int iConstTime = 30;
        private int iTimer = 0;
        private void timer_Queue_Tick(object sender, EventArgs e)
        {
            if (iTimer == 0)
            {
                ZDFP();
                DataGridBind();
                OnSiteSign_Refresh(this, e);
                iTimer = iConstTime;
                //if (FreshTime == null || FreshTime == "")
                //{
                //    FreshTime = "1";
                //}
                //iTimer = int.Parse(FreshTime) * 60;
            }
            else
            {
                iTimer--;
            }
            //btn_Distribution.Text = "分配";
            //btn_Distribution.Text = "分配(" + iTimer.ToString() + ")";
        }

        public void Distribute(DataRow dr)
        {
            TB_Pad_Queue model = new TB_Pad_Queue();
            model.SignedID = dr["SignedID"].ToSafeString();
            model.AllowExamID = dr["AllowExamID"].ToSafeString();
            model.CreateTiime = DateTime.Now;
            model.ExamProvince = dr["ExamProvince"].ToSafeString();
            model.ExamRoomNO = ExamRoomId;
            model.ExamYear = Utility.Helper.SessionerHelper.SystemYear;
            model.GroupNO = dr["GroupNO"].ToSafeString();
            model.IdentityCard = dr["IdentityCard"].ToSafeString();
            model.LotNO = dr["LotNO"].ToSafeString();
            model.Name = dr["Name"].ToSafeString();
            model.NMT_SignUpID = dr["NMT_SignUpID"].ToSafeString();
            model.Remark = "";
            OnSiteSignServiceAttr.SavePadQueue(model);
        }


        public void Distribute(DevExpress.XtraGrid.Views.Grid.GridRow gridRow)
        {
            TB_Pad_Queue model = new TB_Pad_Queue();
            model.SignedID = gridRow.DataRow["SignedID"].ToSafeString();
            model.AllowExamID = gridRow.DataRow["AllowExamID"].ToSafeString();
            model.CreateTiime = DateTime.Now;
            model.ExamProvince = gridRow.DataRow["ExamProvince"].ToSafeString();
            model.ExamRoomNO = ExamRoomId;
            model.ExamYear = Utility.Helper.SessionerHelper.SystemYear;
            model.GroupNO = gridRow.DataRow["GroupNO"].ToSafeString();
            model.IdentityCard = gridRow.DataRow["IdentityCard"].ToSafeString();
            model.LotNO = gridRow.DataRow["LotNO"].ToSafeString();
            model.Name = gridRow.DataRow["Name"].ToSafeString();
            model.NMT_SignUpID = gridRow.DataRow["NMT_SignUpID"].ToSafeString();
            model.Remark = "";
            OnSiteSignServiceAttr.SavePadQueue(model);
        }

        public DevExpress.XtraGrid.Views.Grid.GridView gridView = null;

        public void Distribute()
        {
            int ExamCount = MaxCount;
            int iMax = GetQueueCount(ExamRoomId);
            int iDiffer = ExamCount - iMax;
            if (iDiffer > 0)
            {
                Distribute(iDiffer, ExamRoomId);
                DataGridBind();
            }
        }

        #region 自动分配排队

        public void SetBtnDistributeEnabled(bool isEnabled)
        {
            btn_Distribution.Enabled = isEnabled;
        }
        public int GetQueueCount(string ExamRoomID)
        {
            return OnSiteSignServiceAttr.GetQueueCount(ExamRoomID);
        }

        private void Distribute(int iCount, string ExamRoomID)
        {
            int iNum = 0;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                iNum++;
                if (iNum > iCount)
                {
                    break;
                }
                Distribute(gridView.Rows[i]);
            }
        }
        #endregion

        private void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left && e.Clicks == 2)
            {
                if (e.RowHandle > -1 && (e.Column.ColumnHandle == 2 || e.Column.ColumnHandle == 3))
                {
                    this.DataGridBind();
                    string strSignedID = gridView2.GetFocusedRowCellValue("SignedID_ZB").ToString();
                    using (DataTable dt = OnSiteSignServiceAttr.GetTB_Pad_Examing(strSignedID, ExamRoomId, Utility.Helper.SessionerHelper.SystemYear))
                    {
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            bool flag = OnSiteSignServiceAttr.DeletePadQueue(strSignedID);
                            if (flag)
                            {
                                this.DataGridBind();
                            }
                            OnGridViewDoubleClick(sender, e);
                        }
                        else
                        {
                            DevHelper.ShowErrorMessageBox("该考生已经进入了排队考试，不能进行取消！");
                            this.DataGridBind();
                            return;
                        }
                    }
                }
            }
        }
    }
}
